package controllers.manage.employee;

import controllers.BaseController;
import controllers.auth.Secure;
import controllers.auth.SkipAuth;
import helper.GlobalConfig;
import jodd.util.StringUtil;
import models.admin.AdminUser;
import models.constants.AvailableStatus;
import models.constants.DeletedStatus;
import models.merchant.Merchant;
import play.modules.paginate.JPAExtPaginator;
import play.mvc.Controller;
import play.mvc.With;
import util.common.ConvertUtil;

import java.util.HashMap;
import java.util.Map;

/**
 * 员工
 * Created by hanbin on 17/4/10.
 */
@With(BaseController.class)
public class EmployeeCtrl extends Controller {

    /**
     * 跳转到员工管理页面
     */
    public static void index(Integer pageNumber, String name, String loginName){

        Merchant merchant = Secure.getLoginUser().merchant;

        pageNumber = pageNumber == null ? 1 : pageNumber;
        Map<String , Object> searchMap = new HashMap<>();

        if(StringUtil.isNotBlank(name)) {
            searchMap.put("name", "%"+name+"%");
        }

        if(StringUtil.isNotBlank(loginName)) {
            searchMap.put("loginName", "%"+loginName+"%");
        }

        if(merchant != null){
            searchMap.put("merchantId", merchant.id);
        }

        flash.put("menuId", "3");

        JPAExtPaginator<AdminUser> resultPage = AdminUser.findByCondition(searchMap, "id desc", pageNumber, GlobalConfig.PAGE_SIZE);
        render(resultPage, pageNumber, name, loginName);
    }

    /**
     * 跳转到新增员工页面
     */
    @SkipAuth
    public static void add(){
        render();
    }

    /**
     * 跳转到修改员工页面
     */
    @SkipAuth
    public static void modify(long id, Integer pageNumber){
        AdminUser adminUser = AdminUser.findById(id);
        render(adminUser, pageNumber);
    }


    /**
     * 创建员工
     */
    public static void create(AdminUser adminUser){

        Merchant merchant = Secure.getLoginUser().merchant;
        adminUser.merchant = merchant;

        adminUser.deleted = DeletedStatus.UN_DELETED;
        // 密码加密
        adminUser.password = ConvertUtil.toMD5(adminUser.password);
        adminUser.availableStatus = AvailableStatus.AVAILABLE;
        adminUser.save();
        flash.put("msg" , "员工创建成功");
        redirect("/admin/employee/index/1");
    }

    /**
     * 修改员工
     */
    public static void update(Long id, AdminUser adminUser, Integer pageNumber){
        AdminUser.update(id , adminUser);
        flash.put("msg" , "员工修改成功");
        redirect("/admin/employee/index/"+pageNumber);
    }

    /**
     * 删除员工
     */
    public static void delete(long id , Integer pageNumber){
        pageNumber = pageNumber == null ? 1 : pageNumber;
        AdminUser adminUser = AdminUser.findById(id);
        adminUser.deleted=DeletedStatus.DELETED;
        adminUser.save();
        flash.put("msg" , "员工删除成功");
        redirect("/admin/employee/index/"+pageNumber);
    }

}
